package com.buding.fx.utils;

import com.buding.fx.entity.TreeNode;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mingdongwei-jwk
 * @date 2022/09/15 10:31
 * @class com.buding.fx.utils
 * @Description
 */
public class TreeBuildUtils {

    public static List<TreeNode> buildDeptTreeByStream(List<TreeNode> trees){
        //获取parentId = 0的根节点
        List<TreeNode> list = trees.stream().filter(item -> item.getLevel() == 1L).collect(Collectors.toList());
        //根据parentId进行分组
        Map<Long, List<TreeNode>> map = trees.stream().filter(item -> item.getPid()!=null).collect(Collectors.groupingBy(TreeNode::getPid));
        recursionFnTree(list, map);
        return list;
    }

    /**
     * 递归遍历节点
     * @param list
     * @param map
     */
    public static void recursionFnTree(List<TreeNode> list, Map<Long, List<TreeNode>> map) {
        for (TreeNode treeSelect : list) {
            List<TreeNode> childList = map.get(treeSelect.getId());
            treeSelect.setChidrens(childList);
            if (null != childList && 0 < childList.size()) {
                recursionFnTree(childList, map);
            }
        }

    }
}
